package top.wilsonlv.jaguar.cloud.auth.sdk.token;

import lombok.Getter;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.Assert;

import java.util.Collection;
import java.util.Map;

/**
 * @author lvws
 * @since 2022/1/7
 */
public class DeviceAuthenticationToken extends AbstractAuthenticationToken {

    private final Object principal;

    @Getter
    private final String deviceAuthType;

    @Getter
    private final String deviceUid;

    @Getter
    private final Long timestamp;

    @Getter
    private final String nonce;

    @Getter
    private final String sign;

    @Getter
    private final Map<String, String[]> params;


    public DeviceAuthenticationToken(Object principal, String deviceUid, String deviceAuthType,
                                     Long timestamp, String nonce, String sign, Map<String, String[]> params) {
        super(null);
        this.principal = principal;
        this.deviceAuthType = deviceAuthType;

        this.deviceUid = deviceUid;
        this.timestamp = timestamp;
        this.nonce = nonce;
        this.sign = sign;
        this.params = params;

        setAuthenticated(false);
    }

    public DeviceAuthenticationToken(Object principal, String deviceAuthType, Collection<? extends GrantedAuthority> authorities) {
        super(authorities);
        this.principal = principal;
        this.deviceAuthType = deviceAuthType;
        this.deviceUid = null;
        this.timestamp = null;
        this.nonce = null;
        this.sign = null;
        this.params = null;

        // must use super, as we override
        super.setAuthenticated(true);
    }

    @Override
    public Object getCredentials() {
        return null;
    }

    @Override
    public Object getPrincipal() {
        return this.principal;
    }

    @Override
    public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
        Assert.isTrue(!isAuthenticated,
                "Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
        super.setAuthenticated(false);
    }

}
